//
//  LoginCompanysViewController.m
//  TryShopping
//
//  Created by panquanReabam.com on 16/8/10.
//  Copyright © 2016年 RuiBen. All rights reserved.
//


#import "LoginCompanysViewController.h"
#import "GenerateQRCodeViewController.h"
#import "AddMemberViewController.h"
#import "MJRefresh.h"
#import "TagsCell.h"
#import "LoginCompanysViewCell.h"
#import "MembershipDetailsViewController.h"
#import "TheLoginViewController.h"
#import "LoginCompanysModel.h"
#import "FilterView.h"
#import "MemberSendMsgViewController.h"
#import "ForgotPasswordViewController.h"
#import "ToBindCompanyViewController.h"

@interface LoginCompanysViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate,FilterViewDelegate,LoginCompanysViewCellDelegate>
@end
@implementation LoginCompanysViewController
{
   
    NSMutableArray*modelArray;
   
    UITableView *table;
    MBProgressHUD *progressHud;
    BOOL saveAccount;
    BOOL saveAccount1;
    NSString* TotalCount;
    NSMutableArray*memberIdArray;
    NSMutableArray* memberIdArrays;
    UIView* noDataView;
    UILabel*totalcount;
}
@synthesize alt = alt;
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    saveAccount=YES;
    saveAccount1=NO;

    
}

-(void)update:(NSString *)Str{
    [self setNavigation];
    [self requestData];
    table .frame=CGRectMake(0, 64, ScreenWidth, ScreenHeight);
}
- (void)secondViewController:(ForgotPasswordViewController *)secondViewController updateMemberPhoneText:(NSString *)memberPhoneText{
    [self setNavigation];
    [self requestData];
    table .frame=CGRectMake(0, 64, ScreenWidth, ScreenHeight);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNavigation];
    [self requestData];
}

- (void)switchStores:(NSString *)sender{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue: sender forKey:@"scId"];
//    NSLog(@"-------%@",params);
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData1:@"Common/ChangeLogin" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                
                [Global hideProgressHUDInternal:self.view];
                NSLog(@"switchStores-------%@",severDataDict.dataDict);
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                
               NSMutableArray* funConfigs = [user objectForKey:@"funConfigs"];

                bool bol = false;
                
                //创建俩新的数组
                NSMutableArray *oldArr = [NSMutableArray arrayWithArray:funConfigs];
                NSMutableArray *newArr = [NSMutableArray arrayWithArray:[severDataDict.dataDict  objectForKey:@"funConfigs"]];
                
                
                //对数组1排序。
                
                [oldArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                    return obj1 > obj2;
                }];
                
                [newArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                    return obj1 > obj2;
                }];
                
                
                if (newArr.count == oldArr.count) {
                    
                    bol = true;
                    for (int16_t i = 0; i < oldArr.count; i++) {
                        
                        NSDictionary *c1 = [oldArr objectAtIndex:i];
                        NSDictionary *newc = [newArr objectAtIndex:i];
                        
                        if ((newc!=c1)) {
                            bol = true;
                        
                        }  
                    }  
                }else{
                    bol = false;

                }
                
                if (bol) {   
                    NSLog(@"两个数组的内容相同！"); //首页的不变
                }   
                else {
                    
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent0"];
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent1"];
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent2"];
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent3"];
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"parent4"];

                    NSLog(@"两个数组的内容不相同！");   
                }
                
                [user setObject:[severDataDict.dataDict objectForKey:@"tokenId"] forKey:@"tokenId"];
                [user setObject:[severDataDict.dataDict  objectForKey:@"funConfigs"] forKey:@"funConfigs"];
                [user synchronize];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"changeTokenId" object:nil];
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
               
            }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                
            }
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];

   
    
}

-(void)addoptions:(UIButton *)sender{
    ToBindCompanyViewController * Login=[[ToBindCompanyViewController alloc]init];
    Login.viewSat=@"The original road";
    [self.navigationController pushViewController:Login animated:YES];
}

-(void)requestData{
    
    
    [totalcount removeFromSuperview];
    [noDataView removeFromSuperview];
    modelArray=[[NSMutableArray alloc]init];

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData1:@"Common/LoginCompanys" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"====%@",severDataDict.dataDict);
            
            
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                if (mItemsArray.count>0) {
                    for (NSDictionary *dic in mItemsArray) {
                        LoginCompanysModel *dataModel=[LoginCompanysModel dataModelWithDict:dic];
                        [modelArray addObject:dataModel];
                    }
                }else{
                    noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
                    [self.view addSubview:noDataView];
                    UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                    noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                    [noDataView addSubview:noImage];
                    UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                    noLabel.text=@"没有列表数据，赶紧去添加！";
                    noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                    noLabel.textAlignment=NSTextAlignmentCenter;
                    [noDataView addSubview:noLabel];
                }
                
                [table reloadData];
            }else{
                [Global hideProgressHUDInternal:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController*vc1=[[TheLoginViewController alloc] init];
                    [self.navigationController pushViewController:vc1 animated:YES];
                }
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            //            [Global showTextHudSub:severDataDict.resultStr view:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [modelArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LoginCompanysViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LoginCompanysViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    for (UIView *view in [cell subviews]){
        [view removeFromSuperview];
    }
       
    cell.model=modelArray[indexPath.row];
    cell.mDelegate=self;
    
    
    return cell;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  100;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   }

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}
- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
-(void)setNavigation{
    self.title = @"所属门店";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];

    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.font=[UIFont systemFontOfSize:13];
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    
    
    
    
    UIButton*addBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0, 60/2, 60/2)];
    [addBtn setImage:[UIImage imageNamed:@"tianjia"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addoptions:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
    self.navigationItem.rightBarButtonItem = myBtnBtn;
    
    [table removeFromSuperview];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [table registerClass:[LoginCompanysViewCell class] forCellReuseIdentifier:@"LoginCompanysViewController"];
    [self.view addSubview:table];

    
    
}
-(void)BackAction:(UIButton *)sender{
     [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
//    [self.navigationController popViewControllerAnimated:YES];//选择会员的界面自动退回上一层
    
}

@end
